<?php

/**
 * Copyright (C) 2007 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     @license http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

require_once('../sensapility.php');

/**
 * @author api.jmatt@gmail.com
 * @version 0.1
 */
class SensapilityUnitTests {

  var $emailPref = array(true, false);
  var $entityType = array("Individual", "Business");
  var $url = array("www.foo.com");
  var $webLocale = array("zh_CN", "zh_TW", "cs", "da", "nl", "en", "fi", "fr", 
                         "de", "hu", "it", "ja", "ko", "no", "pl", "pt", "ru", 
                         "sk", "es", "sv", "tr");
  var $commLocale = array("zh_CN", "zh_TW", "cs", "da", "nl", "fi", "fr", "de",
                          "hu", "it", "ja", "ko", "no", "pl", "pt_BR", "ru", 
                          "sk", "es", "sv", "tr", "en_US", "en_GB");
  var $associationStatus = array("NotAssociated", "Pending", "Active");
  var $emailAddressBase = 'unit-tester';
  
  function SensapilityUnitTest() {
    global $SENSAPILITY_AUTH;
    $SENSAPILITY_AUTH->setDebugMode(true);
  }
  
  function testAllPossibleActiveCombinations($verboseMode = true) {
    global $SENSAPILITY_AUTH;
    global $SENSAPILITY_CLIENTS;
    $SENSAPILITY_AUTH->setDebugMode(true);
    $services = array("ContentAds");
    $SENSAPILITY_AUTH->setDebugAssociation($this->associationStatus[2]);
    $acctSrvc = $SENSAPILITY_CLIENTS->getService('Account');

    $emailKeys = array_keys($this->emailPref);
    $entityKeys = array_keys($this->entityType);
    $urlKeys = array_keys($this->url);
    $webKeys = array_keys($this->webLocale); 
    $commKeys = array_keys($this->commLocale);

    $passes = 0;
    $fails = 0;
    $counter = rand(0, 10000000);
    foreach ( $urlKeys as $urlKey ) {
      foreach ( $entityKeys as $entityKey ) {
        foreach ( $emailKeys as $emailKey ) {
          foreach ( $webKeys as $webKey ) {
            foreach ( $commKeys as $commKey ) {
              $pubIds = 
                $acctSrvc->createAdSenseAccount($this->emailAddressBase .
                                                $counter . '@google.com',
                                                $this->entityType[$entityKey],
                                                $this->url[$urlKey],
                                                $this->webLocale[$webKey],
                                                $this->commLocale[$commKey],
                                                $this->emailPref[$emailKey],
                                                $services );
              if ( is_array($pubIds) ) {
                $ids = array();
                $srvcKeys = array_keys($pubIds);
                foreach ( $srvcKeys as $srvcKey ) {
                  $ids[$pubIds[$srvcKey]['type']] = 
                      $pubIds[$srvcKey]['id']; 
                }
                $SENSAPILITY_AUTH->setPubIds($ids);
                $acctSrvc = $SENSAPILITY_CLIENTS->getService('Account');
                
                // verify creation settings
                $actualEmailPref = $acctSrvc->getEmailPromotionsPreference();
                if ( $actualEmailPref == $this->emailPref[$emailKey] ) {
                  $passes++;
                  if ( $verboseMode ) {
                    echo "Email preference matches. -PASS-\n";
                  }
                } else {
                  $fails++;
                  if ( $verboseMode ) {
                    echo "Email preference doesn't match. -FAIL-\n";
                  }
                }
                
                $actualEntityType = $acctSrvc->getEntityType();
                if ( $actualEntityType == $this->entityType[$entityKey] ) {
                  $passes++;
                  if ( $verboseMode ) {
                    echo "Entity type matches. -PASS-\n";
                  }
                } else {
                  $fails++;
                  if ( $verboseMode ) {
                    echo "Entity type doesn't match. -FAIL-\n";
                  }
                }
                
                $actualUserLocale = $acctSrvc->getUsersPreferredLocale();
                if ( $actualUserLocale == $this->commLocale[$commKey] ) {
                  $passes++;
                  if ( $verboseMode ) {
                    echo "User locale matches. -PASS-\n";
                  }
                } else {
                  $fails++;
                  if ( $verboseMode ) {
                    echo "User locale doesn't match. -FAIL-\n";
                  }
                }
                
                $actualWebLocale = $acctSrvc->getWebsiteLocale();
                if ( $actualWebLocale ==  $this->webLocale[$webKey] ) {
                  $passes++;
                  if ( $verboseMode ) {
                    echo "Web locale matches. -PASS-\n";
                  }
                } else {
                  $fails++;
                  if ( $verboseMode ) {
                    echo "Web locale doesn't match. -FAIL-\n";
                  }
                }
                
                $actualWebUrl = $acctSrvc->getWebsiteUrl();
                if ( $actualWebUrl ==  $this->url[$urlKey] ) {
                  $passes++;
                  if ( $verboseMode ) {
                    echo "Url matches. -PASS-\n";
                  }
                } else {
                  $fails++;
                  if ( $verboseMode ) {
                    echo "Url doesn't match. -FAIL-\n";
                  }
                }
              } else {
                // account creation failed
                $fails += 5;
                echo 'Account creation failed with settings: ' .
                     'email-' . $this->emailAddressBase . $counter . 
                     "@google.com \n entity-" . $this->entityType[$entityKey] .
                     "\n" . 'url-' . $this->url[$urlKey] . "\n" .
                     "website locale-" . $this->webLocale[$webKey] . "\n" .
                     "email locale-" . $this->commLocale[$commKey] . "\n" . 
                     "promition prefs - " . $this->emailPref[$emailKey] . "\n";
              }
              $counter++;
              echo "\n";
            }
          }
        }
      }
    }

    echo "Tests passed: " . $passes . "\n";
    echo "Tests failed: " . $fails . "\n";
  }

  /*
   * Create a new AdSense account with all possible association statuses
   * $services - the services the account should have
   */
  function createAccountWithAllStatuses($services, $verboseMode = true) {
    global $SENSAPILITY_AUTH;
    global $SENSAPILITY_CLIENTS;
    $SENSAPILITY_AUTH->setDebugMode(true);
    $passedAll = true;
    $passes = 0;
    $fails = 0;
    $reqNumServices = 0;
    
    $keys = array_keys($services);
    foreach ( $keys as $key ) {
      $reqNumServices++;
    }
    
    $asscKeys = array_keys($this->associationStatus);
    $counter = rand(0, 10000000);
    foreach ( $asscKeys as $asscKey ) {
      if ( $verboseMode ) {
        echo 'Starting test with email: ' . $this->emailAddressBase . 
             $counter . '@google.com' . "\n";
      }
      $SENSAPILITY_AUTH->setDebugAssociation($this->associationStatus[$asscKey]);
      $acctSrvc = $SENSAPILITY_CLIENTS->getService('Account');
      $pubIds = 
        $acctSrvc->createAdSenseAccount($this->emailAddressBase . $counter .
                                        '@google.com',
                                        $this->entityType[0],
                                        $this->url[0],
                                        $this->webLocale[5],
                                        $this->commLocale[20],
                                        $this->emailPref[0],
                                        $services );
      // verify account is opened with one servive and that is content ads
      // verify association type matches
      $pubKeys = array_keys($pubIds);
      $numServices = 0;
      foreach ( $pubKeys as $pubKey ) {
        $numServices++;
      }
      if ( $numServices == $reqNumServices ) {
        $passes++;
        if ( $verboseMode ) {
          echo "Account opened with correct number of services. -PASS-\n";
        }
      } else {
        $passedAll = false;
        $fails++;
        if ( $verboseMode ) {
          echo "Account opened with wrong number of services. -FAIL-\n";
        }
      }
      
      if ( $numServices >= $reqNumServices ) {
        $idKeys = array_keys($pubIds);
        $badMatch = false;
        foreach ( $idKeys as $idKey ) {
          if ( !in_array($pubIds[$idKey]['type'], $services, false) ) {
            $badMatch = true;
          }
        }
        if ( !$badMatch ) {
          $passes++;
          if ( $verboseMode ) {
            echo "Service type(s) correct. -PASS-\n";
          }
        } else {
          $fails++;
          if ( $verboseMode ) {
            echo "Service type(s) incorrect. -FAIL-\n";
          }
        }
      }
      
      // set headers so we can check the association status
      if ( $numServices > 0 ) {
        // take us out of debug mode
        $ids = array($pubIds[0]['type'] => $pubIds[0]['id']);
        $SENSAPILITY_AUTH->setPubIds($ids);
        $acctSrvc = $SENSAPILITY_CLIENTS->getService('Account');
        $asscStatus = $acctSrvc->getAssociationStatus();
        if ( $asscStatus == $this->associationStatus[$asscKey] ) {
          $passes++;
          if ( $verboseMode ) {
            echo "Association status correct. -PASS-\n";
          }
        } else {
          $fails++;
          if ( $verboseMode ) {         
            echo "Association status incorrect. Expected '" . 
                 $this->associationStatus[$asscKey] . "', but is '" . 
                 $asscStatus . "' -FAIL-\n";
          }
        }
      } else {
        if ( $verboseMode ) {
          echo "Unable to check association status, account creation " . 
               "failed. -FAIL-\n";
        }
        $fails++;
      }
      $counter++;
      
      echo "\n";
    }
    echo "Tests passed: " . $passes . "\n";
    echo "Tests failed: " . $fails . "\n";
  }

  function testServiceAddition($verboseMode = true) {

    global $SENSAPILITY_AUTH;
    global $SENSAPILITY_CLIENTS;
    $SENSAPILITY_AUTH->setDebugMode(true);
    $passedAll = true;
    $passes = 0;
    $fails = 0;

    $reqNumServices = 0;
    $services = array('ContentAds', 'ReferralAds');    
    
    $keys = array_keys($services);
    foreach ( $keys as $key ) {
      $reqNumServices++;
    }
    
    $asscKeys = array_keys($this->associationStatus);
    $counter = rand(0, 10000000);
    if ( $verboseMode ) {
      echo 'Starting test with email: ' . $this->emailAddressBase . $counter .
           '@google.com' . "\n";
    }
    $SENSAPILITY_AUTH->setDebugAssociation($this->associationStatus[2]);
    $acctSrvc = $SENSAPILITY_CLIENTS->getService('Account');
    $pubIds = 
        $acctSrvc->createAdSenseAccount($this->emailAddressBase . $counter .
                                        '@google.com',
                                        $this->entityType[0],
                                        $this->url[0],
                                        $this->webLocale[5],
                                        $this->commLocale[20],
                                        $this->emailPref[0],
                                        $services );

    $pubKeys = array_keys($pubIds);
    $numServices = 0;
    foreach ( $pubKeys as $pubKey ) {
      $numServices++;
    }
    if ( $numServices == $reqNumServices ) {
      $passes++;
      if ( $verboseMode ) {
        echo "Account opened with correct number of services. -PASS-\n";
      }
    } else {
      $passedAll = false;
      $fails++;
      if ( $verboseMode ) {
        echo "Account opened with wrong number of services. -FAIL-\n";
      }
    }
    
    // add another service and make sure its there
    $ids = array($pubIds[0]['type'] => $pubIds[0]['id']);
    $SENSAPILITY_AUTH->setPubIds($ids);
    $acctSrvc = $SENSAPILITY_CLIENTS->getService('Account');
    $acctSrvc->addSyndicationService('SearchAds');
    $pubIds = $acctSrvc->getAllSyndicationServices();
    
    $pubKeys = array_keys($pubIds);
    $numServices = 0;
    foreach ( $pubKeys as $pubKey ) {
      $numServices++;
    }
    if ( $numServices == $reqNumServices + 1 ) {
      $passes++;
      if ( $verboseMode ) {
        echo "Account service added. -PASS-\n";
      }
    } else {
      $passedAll = false;
      $fails++;
      if ($verboseMode) {
        echo "Account not added. -FAIL-\n";
      }
    }
    echo "Tests passed: " . $passes . "\n";
    echo "Tests failed: " . $fails . "\n";
  }

  function testSettingEmailPrefs($verboseMode = true){

    global $SENSAPILITY_AUTH;
    global $SENSAPILITY_CLIENTS;
    $SENSAPILITY_AUTH->setDebugMode(true);
    $passedAll = true;
    $passes = 0;
    $fails = 0;

    $reqNumServices = 0;
    $services = array('ContentAds', 'ReferralAds');    
    
    $keys = array_keys($services);
    foreach ( $keys as $key ) {
      $reqNumServices++;
    }

    $counter = rand(0, 10000000);
    if ( $verboseMode ) {
      echo 'Starting test with email: ' . $this->emailAddressBase . $counter .
           '@google.com' . "\n";
    }
    $SENSAPILITY_AUTH->setDebugAssociation($this->associationStatus[2]);
    $acctSrvc = $SENSAPILITY_CLIENTS->getService('Account');
    $pubIds = 
      $acctSrvc->createAdSenseAccount($this->emailAddressBase . $counter .
                                      '@google.com',
                                      $this->entityType[0],
                                      $this->url[0],
                                      $this->webLocale[5],
                                      $this->commLocale[20],
                                      $this->emailPref[0],
                                      $services );

    $ids = array($pubIds[0]['type'] => $pubIds[0]['id']);
    $SENSAPILITY_AUTH->setPubIds($ids);
    $acctSrvc = $SENSAPILITY_CLIENTS->getService('Account');

    $actualEmailPref = $acctSrvc->getEmailPromotionsPreference();
    if ( $actualEmailPref == $this->emailPref[0] ) {
      $passes++;
      if ( $verboseMode ) {
        echo "Promotions preferences set correctly on account open. -PASS-\n";
      } 
    } else {
      $fails++;
      if ( $verboseMode ) {
        echo "Promotions preferences NOT set correctly on account open." . 
          " -FAIL-\n";
      }
    }

    $acctSrvc->setEmailPromotionsPreference($this->emailPref[1]);
    
    $actualEmailPref = $acctSrvc->getEmailPromotionsPreference();
    if ( $actualEmailPref == $this->emailPref[1] ) {
      $passes++;
      if ( $verboseMode ) {
        echo "Promotions preferences reset correctly. -PASS-\n";
      } 
    } else {
      $fails++;
      if ( $verboseMode ) {
        echo "Promotions preferences NOT reset correctly. -FAIL-\n";
      }
    }
    echo "Tests passed: " . $passes . "\n";
    echo "Tests failed: " . $fails . "\n";
  }


  function testSettingUserLocale($verboseMode = true){

    global $SENSAPILITY_AUTH;
    global $SENSAPILITY_CLIENTS;
    $SENSAPILITY_AUTH->setDebugMode(true);
    $passedAll = true;
    $passes = 0;
    $fails = 0;

    $reqNumServices = 0;
    $services = array('ContentAds', 'ReferralAds');    
    
    $keys = array_keys($services);
    foreach ( $keys as $key ) {
      $reqNumServices++;
    }

    $counter = rand(0, 10000000);
    if ( $verboseMode ) {
      echo 'Starting test with email: ' . $this->emailAddressBase . $counter .
           '@google.com' . "\n";
    }
    $SENSAPILITY_AUTH->setDebugAssociation($this->associationStatus[2]);
    $acctSrvc = $SENSAPILITY_CLIENTS->getService('Account');
    $pubIds = 
      $acctSrvc->createAdSenseAccount($this->emailAddressBase . $counter .
                                      '@google.com',
                                      $this->entityType[0],
                                      $this->url[0],
                                      $this->webLocale[5],
                                      $this->commLocale[20],
                                      $this->emailPref[0],
                                      $services );

    $ids = array($pubIds[0]['type'] => $pubIds[0]['id']);
    $SENSAPILITY_AUTH->setPubIds($ids);
    $acctSrvc = $SENSAPILITY_CLIENTS->getService('Account');

    $actualuserLocale = $acctSrvc->getUsersPreferredLocale();
    if ( $actualuserLocale == $this->commLocale[20] ) {
      $passes++;
      if ( $verboseMode ) {
        echo "User locale set correctly on account open. -PASS-\n";
      } 
    } else {
      $fails++;
      if ( $verboseMode ) {
        echo "User locale NOT set correctly on account open. -FAIL-\n";
      }
    }

    $acctSrvc->setUsersPreferredLocale($this->commLocale[19]);
    
    $actualuserLocale = $acctSrvc->getUsersPreferredLocale();
    if ( $actualuserLocale == $this->commLocale[19] ) {
      $passes++;
      if ( $verboseMode ) {
        echo "User locale reset correctly. -PASS-\n";
      } 
    } else {
      $fails++;
      if ( $verboseMode ) {
        echo "User locale NOT reset correctly. -FAIL-\n";
      }
    }
    echo "Tests passed: " . $passes . "\n";
    echo "Tests failed: " . $fails . "\n";
  }

  function testAssociation($verboseMode = true){

    global $SENSAPILITY_AUTH;
    global $SENSAPILITY_CLIENTS;
    $SENSAPILITY_AUTH->setDebugMode(true);
    $passedAll = true;
    $passes = 0;
    $fails = 0;

    $reqNumServices = 0;
    $services = array('ContentAds', 'ReferralAds');    
    
    $keys = array_keys($services);
    foreach ( $keys as $key ) {
      $reqNumServices++;
    }

    $counter = rand(0, 10000000);
    if ( $verboseMode ) {
      echo 'Starting test with email: ' . $this->emailAddressBase . $counter .
           '@google.com' . "\n";
    }

    // create non-associated account
    $SENSAPILITY_AUTH->setDebugAssociation($this->associationStatus[0]);
    $acctSrvc = $SENSAPILITY_CLIENTS->getService('Account');
    $pubIds = 
      $acctSrvc->createAdSenseAccount($this->emailAddressBase . $counter .
                                      '@google.com',
                                      $this->entityType[0],
                                      $this->url[0],
                                      $this->webLocale[5],
                                      $this->commLocale[20],
                                      $this->emailPref[0],
                                      $services );

    $ids = array($pubIds[0]['type'] => $pubIds[0]['id']);
    $SENSAPILITY_AUTH->setPubIds($ids);
    $acctSrvc = $SENSAPILITY_CLIENTS->getService('Account');

    $asscStatus = $acctSrvc->getAssociationStatus();
    if ( $asscStatus == $this->associationStatus[0] ) {
      $passes++;
      if ( $verboseMode ) {
        echo "Association status correct. -PASS-\n";
      } 
    } else {
      $fails++;
      if ( $verboseMode ) {
        echo "Association status incorrect. -FAIL-\n";
      }
    }
    $SENSAPILITY_AUTH->setDebugAssociation($this->associationStatus[2]);
    $acctSrvc = $SENSAPILITY_CLIENTS->getService('Account');
    $acctSrvc->associateExistingAccount($this->emailAddressBase . $counter .
                                        '@google.com', "12345", "67890");
   
    $asscStatus = $acctSrvc->getAssociationStatus();
    // the headers are ignored which prevent immediate association
    // accept either pending or active status in anticipation that these
    // headers will no longer be ignored at some point
    if ( $asscStatus == $this->associationStatus[1] || 
         $asscStatus == $this->associationStatus[2] ) {
      $passes++;
      if ( $verboseMode ) {
        echo "Association status correct. -PASS-\n";
      } 
    } else {
      $fails++;
      if ( $verboseMode ) {
        echo "Association status incorrect. -FAIL-\n";
      }
    }
    echo "Tests passed: " . $passes . "\n";
    echo "Tests failed: " . $fails . "\n";
  }

  function testUrlChannel() {
    global $SENSAPILITY_AUTH;
    global $SENSAPILITY_CLIENTS;

    $passes = 0;
    $fails = 0;

    $channelAddr = 'www.foo.com/baz.html';
    $channelStatus = 'Inactive';
    $channelType = 'Url';
    $channelStatusUpdate = 'Active';

    $newAcct = $this->makeNewAccount();

    $keys = array_keys($newAcct);
    
    $idArray = array();
    $pubId = $newAcct[$keys[0]]['id'];
    $idArray['ContentAds'] = $pubId;
    $SENSAPILITY_AUTH->setPubIds($idArray);

    $chnServ = $SENSAPILITY_CLIENTS->getService('Channel');
    $newChannel =  $chnServ->createChannel($channelAddr,
                                           $channelStatus,
                                           $pubId,
                                           $channelType);
    $channelId = $newChannel['id'];
    
    $verifyChannel = $chnServ->getChannel($channelId);
    if ( $verifyChannel['name'] == $channelAddr &&
         $verifyChannel['status'] == $channelStatus &&
         $verifyChannel['type'] == $channelType ) {
      $passes++;
      echo "Channel " . $verifyChannel['id'] . " created correctly. -PASS- \n";
    } else {
      $fails++;
      echo "Channel created incorrectly. -FAIL- \n";
    }

    $chnServ->updateChannel($channelId, 
                            $channelAddr, 
                            $channelStatusUpdate, 
                            $pubId,
                            $channelType);

    $verifyChannel = $chnServ->getChannel($channelId);
    if ( $verifyChannel['name'] == $channelAddr &&
         $verifyChannel['status'] == $channelStatusUpdate &&
         $verifyChannel['type'] == $channelType ) {
      $passes++;
      echo "Channel " . $verifyChannel['id'] . " updated correctly. -PASS- \n";
    } else {
      $fails++;
      echo "Channel update incorrectly. -FAIL- \n";
    }

    $chnServ->deleteChannel($channelId);

    $verifyChannel = $chnServ->getChannel($channelId);
    if ( is_null($verifyChannel) ) {
      echo "Channel " . $verifyChannel['id'] . " deleted successfully.\n";
      $passes++;
    } else {
      echo "Channel deletion failed.\n";
      $fails++;
    }
    echo "Tests passed: " . $passes . "\n";
    echo "Tests failed: " . $fails . "\n";
  }

  function testCustomChannel() {
    global $SENSAPILITY_AUTH;
    global $SENSAPILITY_CLIENTS;

    $passes = 0;
    $fails = 0;

    $channelAddr = 'MyChannel1';
    $channelStatus = 'Inactive';
    $channelType = 'Custom';
    $channelStatusUpdate = 'Active';
    $channelAddrUpdate = 'MyChannel2';
    
    $newAcct = $this->makeNewAccount();

    $keys = array_keys($newAcct);
    
    $idArray = array();
    $pubId = $newAcct[$keys[0]]['id'];
    $idArray['ContentAds'] = $pubId;
    $SENSAPILITY_AUTH->setPubIds($idArray);

    $chnServ = $SENSAPILITY_CLIENTS->getService('Channel');
    $newChannel =  $chnServ->createChannel($channelAddr,
                                           $channelStatus,
                                           $pubId,
                                           $channelType);
    $channelId = $newChannel['id'];
    
    $verifyChannel = $chnServ->getChannel($channelId);
    if ( $verifyChannel['name'] == $channelAddr &&
         $verifyChannel['status'] == $channelStatus &&
         $verifyChannel['type'] == $channelType ) {
      $passes++;
      echo "Channel created correctly. -PASS- \n";
    } else {
      $fails++;
      echo "Channel created incorrectly. -FAIL- \n";
    }

    $chnServ->updateChannel($channelId, 
                            $channelAddrUpdate, 
                            $channelStatusUpdate, 
                            $pubId,
                            $channelType);

    $verifyChannel = $chnServ->getChannel($channelId);
    if ( $verifyChannel['name'] == $channelAddrUpdate &&
         $verifyChannel['status'] == $channelStatusUpdate &&
         $verifyChannel['type'] == $channelType ) {
      $passes++;
      echo "Channel updated correctly. -PASS- \n";
    } else {
      $fails++;
      echo "Channel update incorrectly. -FAIL- \n";
    }

    $chnServ->deleteChannel($channelId);

    $verifyChannel = $chnServ->getChannel($channelId);
    if ( is_null($verifyChannel) ) {
      echo "Channel deleted successfully.\n";
      $passes++;
    } else {
      echo "Channel deletion failed.\n";
      $fails++;
    }
    echo "Tests passed: " . $passes . "\n";
    echo "Tests failed: " . $fails . "\n";
  }

  /**
   * Test operations executed on multiple channels
   */
  function testMultiChannelOps() {
    global $SENSAPILITY_CLIENTS;
    global $SENSAPILITY_AUTH;

    $newAcct = $this->makeNewAccount();

    $keys = array_keys($newAcct);
    
    $idArray = array();
    $pubId = $newAcct[$keys[0]]['id'];
    $idArray['ContentAds'] = $pubId;
    $SENSAPILITY_AUTH->setPubIds($idArray);

    $channels = array();

    $channelOne = array();
    $channelOne['name'] = 'www.apple.com/foo.bar';
    $channelOne['status'] = 'Active';
    $channelOne['synServiceId'] = $pubId;
    $channelOne['type'] = 'Url';
    $channelOneNewStatus = 'Inactive';

    $channelTwo = array();
    $channelTwo['name'] = 'www.apple.com/foo.baz';
    $channelTwo['status'] = 'Active';
    $channelTwo['synServiceId'] = $pubId;
    $channelTwo['type'] = 'Url';

    $channelThree = array();
    $channelThree['name'] = 'Custom1';
    $channelThree['status'] = 'Active';
    $channelThree['synServiceId'] = $pubId;
    $channelThree['type'] = 'Custom';

    $channelFour = array();
    $channelFour['name'] = 'Custom2';
    $channelFour['status'] = 'Active';
    $channelFour['synServiceId'] = $pubId;
    $channelFour['type'] = 'Custom';
    $channelFourNewName = 'Channel4';

    $channels[0] = $channelOne;
    $channels[1] = $channelTwo;
    $channels[2] = $channelThree;
    $channels[3] = $channelFour;

    $chnSrvc = $SENSAPILITY_CLIENTS->getService('Channel');

    $newChannels = $chnSrvc->createChannels($channels);
    $keys = array_keys($newChannels);
    $counter = 0;
    $passes = 0;
    $fails = 0;

    $newChannelIds = array();

    // create four new channels
    foreach($keys as $key) {
      $thisChannel = $newChannels[$key];
      if ($channels[$counter]['name'] == $thisChannel['name'] &&
          $channels[$counter]['status'] == $thisChannel['status'] &&
          $channels[$counter]['type'] == $thisChannel['type'] &&
          $channels[$counter]['synServiceId']==$thisChannel['synServiceId']) {
        $passes++;
        $newChannelIds[$counter] = $thisChannel['id'];
        echo 'Channel ' . $thisChannel['id'] . " created successfully. " . 
             "-PASS-\n";
      } else {
        $fails++;
        echo 'Channel ' . $thisChannel['id'] . " creation failed. -FAIL-\n";
      }
      $counter++;
    }

    //delete two channels
    $deleteTargets = array();
    $remainingChannels = array();
    $deleteTargets[0] = $newChannels[1]['id'];
    $deleteTargets[1] = $newChannels[2]['id'];
    $remainingChannels[0] = $newChannels[0];
    $remainingChannels[1] = $newChannels[3];
    $chnSrvc->deleteChannels($deleteTargets);

    // getChannel requests should fail
    $req = $chnSrvc->getChannels($deleteTargets);
    
    if ( is_null($req) ) {
      echo "Two channels deleted successfully.-PASS-\n";
      $passes++;
    } else {
      echo "Failed deleting two channels. -FAIL-\n";
      $fails++;
    }
    
    // update channels
    $remainingChannels[0]['status'] = $channelOneNewStatus;
    $remainingChannels[1]['name'] = $channelFourNewName;
    $chnSrvc->updateChannels($remainingChannels);

    $keys = array_keys($remainingChannels);
    $counter = 0;
    foreach ($keys as $key) {
      $thisChannel = $chnSrvc->getChannel( $remainingChannels[$key]['id'] );
      if ( $remainingChannels[$counter]['name'] == $thisChannel['name'] &&
           $remainingChannels[$counter]['status'] == $thisChannel['status'] &&
           $remainingChannels[$counter]['type'] == $thisChannel['type'] &&
           $remainingChannels[$counter]['synServiceId'] == 
               $thisChannel['synServiceId'] ) {
          $passes++;
          echo '`Channel ' . $thisChannel['id'] . ' updated correctly.' . 
               " -PASS-\n";
        } else {
          $fails++;
          echo 'Channel ' . $thisChannel['id'] . ' updated incorrectly.' . 
               " -FAIL-\n";
        }
        $counter++;
      }
      echo 'Tests passed: ' . $passes . "\n";
      echo 'Tests faield: ' . $fails . "\n";
  }


  function makeNewAccount($accountType = "ContentAds") {
    global $SENSAPILITY_CLIENTS;
    global $SENSAPILITY_AUTH;

    $SENSAPILITY_AUTH->setDebugMode(true);
    $SENSAPILITY_AUTH->setDebugAssociation($this->associationStatus[2]);
    $acctSrvc = $SENSAPILITY_CLIENTS->getService('Account');
    $acctSuffix = rand(0,10000000);
    
    $newAcct = $acctSrvc->createAdSenseAccount($this->emailAddressBase . 
                                                   $acctSuffix . '@google.com',
                                               'Individual',
                                               'http://www.foo.com',
                                               'en',
                                               'en_US',
                                               true,
                                               array($accountType));
    return $newAcct;
  }

  function testGenerateAfcCode() {
    global $SENSAPILITY_CLIENTS;
    global $SENSAPILITY_AUTH;

    $passes = 0;
    $fails = 0;

    $newAcct = $this->makeNewAccount('ContentAds');

    $idArray = array();
    $keys = array_keys($newAcct);
    $pubId = $newAcct[$keys[0]]['id'];
    $idArray['ContentAds'] = $pubId;
    $SENSAPILITY_AUTH->setPubIds($idArray);

    $adStyle = array();
    $adStyle['name'] = 'Seaside';
    $adStyle['borderColor'] = '#000000';
    $adStyle['backgroundColor'] = '#000000';
    $adStyle['titleColor'] = '#FFFFFF';
    $adStyle['textColor'] = '#FFFFFF';
    $adStyle['urlColor'] = '#FF66FF';

    $afc = $SENSAPILITY_CLIENTS->getService('AdSenseForContent');
    $adCode = $afc->generateAdCode($pubId, 
                                   $adStyle, 
                                   'TextOnly', 
                                   '120x600', 
                                   '#FFFFFF', 
                                   false, 
                                   null);
    if ( !is_null($adCode) ) {
      $passes +=1 ;
      echo "Ad code generated correctly. -PASS-\n";
    } else {
      $fails++;
      echo "Ad code generation failed. -FAIL-\n";
    }
    $this->_doPassFailOutput($passes, $fails, 'testGenerateAfcCode');
  }

  function testAfcStyle() {
    global $SENSAPILITY_CLIENTS;
    global $SENSAPILITY_AUTH;

    $passes = 0;
    $fails = 0;

    $newAcct = $this->makeNewAccount('ContentAds');

    $idArray = array();
    $keys = array_keys($newAcct);
    $pubId = $newAcct[$keys[0]]['id'];
    $idArray['ContentAds'] = $pubId;
    $SENSAPILITY_AUTH->setPubIds($idArray);

    $afc = $SENSAPILITY_CLIENTS->getService('AdSenseForContent');
    $builtinStyles = $afc->getBuiltinAdStyles();

    if ( !is_null($builtinStyles) ) {
      $passes++;
      echo "Built-in styles retreived. -PASS-\n";
    } else {
      $fails++;
      echo "Built-in style retrieval failed. -FAIL-\n";
    }

    $keys = array_keys($builtinStyles);
    $builtinStyles[$keys[0]]['name'] = 'Custom1';
    $custom = $builtinStyles[$keys[0]];

    $afc->saveAdStyle($pubId, 
                      $custom['backgroundColor'],
                      $custom['borderColor'],
                      $custom['name'],
                      $custom['textColor'],
                      $custom['titleColor'],
                      $custom['urlColor']);

    $savedStyle = $afc->getAdStyle($pubId, 'Custom1');

    if ( $savedStyle && 
         $savedStyle['backgroundColor'] == $custom['backgroundColor'] &&
         $savedStyle['borderColor'] == $custom['borderColor'] && 
         $savedStyle['name'] == $custom['name'] && 
         $savedStyle['textColor'] == $custom['textColor'] && 
         $savedStyle['titleColor'] == $custom['titleColor'] &&
         $savedStyle['urlColor'] == $custom['urlColor']) {
      echo "Style retreived. -PASS-\n";
      $passes++;
    } else {
      $fails++;
      echo "Style not found. -FAIL-\n";
    }
    $custom2 = $custom;
    $custom2['name'] = 'Custom2';
    $afc->saveAdStyle($pubId, 
                      $custom2['backgroundColor'],
                      $custom2['borderColor'],
                      $custom2['name'],
                      $custom2['textColor'],
                      $custom2['titleColor'],
                      $custom2['urlColor']);
    $savedStyle = $afc->getAdStyle($pubId, 'Custom2');

    if ( $savedStyle && 
         $savedStyle['backgroundColor'] == $custom2['backgroundColor'] &&
         $savedStyle['borderColor'] == $custom2['borderColor'] && 
         $savedStyle['name'] == $custom2['name'] && 
         $savedStyle['textColor'] == $custom2['textColor'] && 
         $savedStyle['titleColor'] == $custom2['titleColor'] &&
         $savedStyle['urlColor'] == $custom2['urlColor']) {
      echo "Style retreived. -PASS-\n";
      $passes++;
    } else {
      echo "Style not found. -FAIL-\n";
      $fails++;
    }

    // this request should fail
    $savedStyle = $afc->getAdStyle($pubId, 'Custom3');
    if ( $savedStyle ) {
      echo "Non-existant style returned result. -FAIL-\n";
      $fails++;
    } else {
      echo "Non-existant style not found. -PASS-\n";
      $passes++;
    }

    $afc->deleteAdStyle($pubId, 'Custom1');
    $savedStyle = $afc->getAdStyle($pubId, 'Custom1');
    if ( $savedStyle ) {
      echo "Non-existant style returned result. -FAIL-\n";
      $fails++;
    } else {
      echo "Non-existant style not found. -PASS-\n";
      $passes++;
    }

    $this->_doPassFailOutput($passes, $fails, 'testAfcStyle');
  }

  function testAfcMultiStyle() {
    global $SENSAPILITY_CLIENTS;
    global $SENSAPILITY_AUTH;

    $passes = 0;
    $fails = 0;

    $newAcct = $this->makeNewAccount('ContentAds');

    $idArray = array();
    $keys = array_keys($newAcct);
    $pubId = $newAcct[$keys[0]]['id'];
    $idArray['ContentAds'] = $pubId;
    $SENSAPILITY_AUTH->setPubIds($idArray);

    $afc = $SENSAPILITY_CLIENTS->getService('AdSenseForContent');

    $builtIn = $afc->getBuiltinAdStyles();
    $keys = array_keys($builtIn);
    $customs = array();
    $customs[0] = $builtIn[$keys[0]];
    $customs[1] = $builtIn[$keys[1]];
    $customs[2] = $builtIn[$keys[2]];
    $customs[3] = $builtIn[$keys[3]];

    $customs[0]['name'] = 'Custom1';
    $customs[1]['name'] = 'Custom2';
    $customs[2]['name'] = 'Custom3';
    $customs[3]['name'] = 'Custom4';

    $afc->saveAdStyles($pubId, $customs);
    $styles = $afc->getAdStyles($pubId);

    // check to see that there are four user-defined styles
    // and that they match the ones we saved

    $keys = array_keys($styles);
    $counter = 0;
    foreach ( $keys as $key ) {
      $thisStyle = $styles[$key];
      if ( $thisStyle && 
           $thisStyle['backgroundColor'] == 
                $customs[$counter]['backgroundColor'] &&
           $thisStyle['borderColor'] == $customs[$counter]['borderColor'] && 
           $thisStyle['name'] == $customs[$counter]['name'] && 
           $thisStyle['textColor'] == $customs[$counter]['textColor'] && 
           $thisStyle['titleColor'] == $customs[$counter]['titleColor'] &&
           $thisStyle['urlColor'] == $customs[$counter]['urlColor']) {
        $passes++;
        echo 'Style ' . $counter . " matches. -PASS- \n";
      } else {
        $fails++;
        echo 'Style ' . $counter . " doesn't match. -FAIL- \n";
      }
      $counter++;
    }

    $afc->deleteAdStyles($pubId, array('Custom1', 'Custom3'));

    $styles = $afc->getAdStyles($pubId);

    // check to see that there are four user-defined styles
    // and that they match the ones we saved

    $keys = array_keys($styles);
    $counter = 0;
    foreach ( $keys as $key ) {
      $counter++;
    }

    if ( $counter == 2 ) {
      echo "Delete successful. -PASS-\n";
      $passes++;
    } else {
      echo "Delete failed. -FAIL-\n";
      $fails++;
    }
    $this->_doPassFailOutput($passes, $fails, 'testAfcMultiStyle');
  }

  function testAdLayouts() {
    global $SENSAPILITY_CLIENTS;
    global $SENSAPILITY_AUTH;

    $passes = 0;
    $fails = 0;

    $newAcct = $this->makeNewAccount('ContentAds');

    $idArray = array();
    $keys = array_keys($newAcct);
    $pubId = $newAcct[$keys[0]]['id'];
    $idArray['ContentAds'] = $pubId;
    $SENSAPILITY_AUTH->setPubIds($idArray);

    $afc = $SENSAPILITY_CLIENTS->getService('AdSenseForContent');

    $adUnitTypes = array();
    $adUnitTypes[0] = 'TextOnly';
    $adUnitTypes[1] = 'ImageOnly';
    $adUnitTypes[2] = 'TextAndImage';
    $adUnitTypes[3] = 'FourLinkUnit';
    $adUnitTypes[4] = 'FiveLinkUnit';

    $counter = 4;

    while ( $counter > -1 ) {
      $layouts = $afc->getAdLayouts($adUnitTypes[$counter]);
      if ( !is_null($layouts) && $layouts ) {
        $passes++;
        echo $adUnitTypes[$counter] . " returned results. -PASS-\n";
      } else {
        $fails++;
        echo $adUnitTypes[$counter] . " did not return results. -FAIL-\n";
      }
      $counter--;
    }
    $this->_doPassFailOutput($passes, $fails, 'testAdLayouts');
  }

  function testAdUnitTypes() {
    global $SENSAPILITY_CLIENTS;
    global $SENSAPILITY_AUTH;

    $passes = 0;
    $fails = 0;

    $newAcct = $this->makeNewAccount('ContentAds');

    $idArray = array();
    $keys = array_keys($newAcct);
    $pubId = $newAcct[$keys[0]]['id'];
    $idArray['ContentAds'] = $pubId;
    $SENSAPILITY_AUTH->setPubIds($idArray);

    $afc = $SENSAPILITY_CLIENTS->getService('AdSenseForContent');

    $adlayouts = array();
    $adlayouts[0] = '728x90';
    $adlayouts[1] = '468x60';
    $adlayouts[2] = '300x250';
    $adlayouts[3] = '160x600';
    $adlayouts[4] = '120x600';
    $adlayouts[5] = '336x280';
    $adlayouts[6] = '250x250';
    $adlayouts[7] = '234x60';
    $adlayouts[8] = '180x150';
    $adlayouts[9] = '125x125';
    $adlayouts[10] = '120x240';
    $adlayouts[11] = '728x15';


    $counter = 11;

    while ( $counter > -1 ) {
      $unitTypes = $afc->getAdUnitTypes($adlayouts[$counter]);
      if ( !is_null($unitTypes) && $unitTypes ) {
        $passes++;
        echo $adlayouts[$counter] . " returned results. -PASS-\n";
      } else {
        $fails++;
        echo $adlayouts[$counter] . " did not return results. -FAIL-\n";
      }
      $counter--;
    }
    $this->_doPassFailOutput($passes, $fails, 'testAdUnitTypes');
  }

  /**
   * @param string $serviceName 'AdSenseForContent' or 'AdSenseForSearch'
   */
  function testServiceChannels($serviceName) {
    global $SENSAPILITY_CLIENTS;
    global $SENSAPILITY_AUTH;

    $passes = 0;
    $fails = 0;

    $newAcct = "";
    if ($serviceName == 'AdSenseForContent') {
      $newAcct = $this->makeNewAccount('ContentAds');
    } else {
      $newAcct = $this->makeNewAccount('SearchAds');
    }

    $idArray = array();
    $keys = array_keys($newAcct);
    $pubId = $newAcct[$keys[0]]['id'];
    $idArray[$newAcct[$keys[0]]['type']] = $pubId;
    $SENSAPILITY_AUTH->setPubIds($idArray);

    $afc = $SENSAPILITY_CLIENTS->getService($serviceName);

    // there should be no channels to begin with, verify this
    $results = $this->_getAfcChannels($afc, 
                                      $pubId, 
                                      false, 
                                      false, 
                                      false, 
                                      false, 
                                      false, 
                                      false);
    $passes += $results[0];
    $fails += $results[1];

    $chnSrvc = $SENSAPILITY_CLIENTS->getService('Channel');
    $chnSrvc->createChannel('foo', 'Active', $pubId, 'Custom');
    $results = $this->_getAfcChannels($afc, 
                                      $pubId, 
                                      false, 
                                      true, 
                                      false, 
                                      false, 
                                      false, 
                                      true);
    $passes += $results[0];
    $fails += $results[1];

    $chnSrvc->createChannel('foo2', 'Inactive', $pubId, 'Custom');
    $results = $this->_getAfcChannels($afc, 
                                      $pubId, 
                                      false, 
                                      true, 
                                      false, 
                                      true, 
                                      false, 
                                      true);    
    $passes += $results[0];
    $fails += $results[1];
    
    $chnSrvc->createChannel('www.apple.com', 'Inactive', $pubId, 'Url');
    echo $chnSrvc->__soapClient->response . "\n";
    $results = $this->_getAfcChannels($afc, 
                                      $pubId, 
                                      true, 
                                      true, 
                                      true, 
                                      true, 
                                      false, 
                                      true);
    $passes += $results[0];
    $fails += $results[1];

    $chnSrvc->createChannel('www.apple.com/a.html', 'Active', $pubId, 'Url');
    $results = $this->_getAfcChannels($afc, 
                                      $pubId, 
                                      true, 
                                      true, 
                                      true, 
                                      true, 
                                      true, 
                                      true);
    $passes += $results[0];
    $fails += $results[1];

    $this->_doPassFailOutput($passes, 
                             $fails, 
                             'testServiceChannels - ' . $serviceName);
  }

  function _getAfcChannels($serviceObject, 
                           $pubId,
                           $expectUrlChannels, 
                           $expectCustomChannels,
                           $expectInactiveUrlChannels,
                           $expectInactiveCustomChannels, 
                           $expectActiveUrlChannels,
                           $expectActiveCustomChannels) {
    $passes = 0;
    $fails = 0;
    $channels = $serviceObject->getChannels($pubId,'Url');
    /* if ($expectUrlChannels) {
      echo "\n\n" . $serviceObject->__soapClient->request . "\n";
      echo $serviceObject->__soapClient->response . "\n\n";
      }*/
    if ( (bool)$channels == $expectUrlChannels ) {
      $passes++;
      echo "Url channel had expected return. -PASS-\n";
    } else {
      echo "Url channel had unexpected return. -FAIL-\n";
      $fails++;
    }
    
    $channels = $serviceObject->getChannels($pubId,'Custom');
    if ( (bool)$channels == $expectCustomChannels ) {
      $passes++;
      echo "Custom channel had expected return. -PASS-\n";
    } else {
      echo "Custom channel had unexpected return. -FAIL-\n";
      $fails++;
    }

    $channels = $serviceObject->getInactiveChannels($pubId,'Url');
    if ( (bool)$channels == $expectInactiveUrlChannels ) {
      $passes++;
      echo "Inactive url channel had expected return. -PASS-\n";
    } else {
      echo "Inactive url channel had unexpected return. -FAIL-\n";
      $fails++;
    }
    
    $channels = $serviceObject->getInactiveChannels($pubId,'Custom');
    if ( (bool)$channels == $expectInactiveCustomChannels ) {
      $passes++;
      echo "Inactive custom channel had expected return. -PASS-\n";
    } else {
      echo "Inactive custom channel had unexpected return. -FAIL-\n";
      $fails++;
    }

    $channels = $serviceObject->getActiveChannels($pubId,'Url');
    if ( (bool)$channels == $expectActiveUrlChannels ) {
      $passes++;
      echo "Active url channel had expected return. -PASS-\n";
    } else {
      echo "Active url channel had unexpected return. -FAIL-\n";
      $fails++;
    }
    
    $channels = $serviceObject->getActiveChannels($pubId,'Custom');
    if ( (bool)$channels == $expectActiveCustomChannels ) {
      $passes++;
      echo "Active custom channel had expected return. -PASS-\n";
    } else {
      echo "Active custom channel had unexpected return. -FAIL-\n";
      $fails++;
    }

    return array($passes, $fails);
  }

  function testAfsCodeGeneration(){
    global $SENSAPILITY_CLIENTS;
    global $SENSAPILITY_AUTH;

    $passes = 0;
    $fails = 0;

    $newAcct = $this->makeNewAccount("SearchAds");

    $idArray = array();
    $keys = array_keys($newAcct);
    $pubId = $newAcct[$keys[0]]['id'];
    $idArray['SearchAds'] = $pubId;
    $SENSAPILITY_AUTH->setPubIds($idArray);

    $afs = $SENSAPILITY_CLIENTS->getService('AdSenseForSearch');
    $srchCode =  $afs->generateSearchBoxCode($pubId, 
                                             'US', 
                                             'GoogleSearch',
                                             'ISO-8859-1',
                                             'en',
                                             false,
                                             false,
                                             null,
                                             null,
                                             '#FFFFFF',
                                             true,
                                             true,
                                             true,
                                             'GoogleLogo',
                                             'Snowcone',
                                             20,
                                             '#FF66FF',
                                             null);

    if (is_null($srchCode)) {
      $fails++;
      echo "testAFSCodeGeneration: Producing search code failed. -FAIL-\n";
    } else {
      $passes++;
      echo "testAFSCodeGeneration: Producing search code successful. -PASS-\n";
    }

    $this->_doPassFailOutput($passes, $fails, 'testAFSCodeGeneration');
  }

  function testGetSearchResultStyles() {
    global $SENSAPILITY_CLIENTS;
    global $SENSAPILITY_AUTH;

    $passes = 0;
    $fails = 0;

    $newAcct = $this->makeNewAccount("SearchAds");

    $idArray = array();
    $keys = array_keys($newAcct);
    $pubId = $newAcct[$keys[0]]['id'];
    $idArray['SearchAds'] = $pubId;
    $SENSAPILITY_AUTH->setPubIds($idArray);

    $afs = $SENSAPILITY_CLIENTS->getService('AdSenseForSearch');
    $resultStyles = $afs->getSearchResultStyles($pubId);

    if (!is_null($resultStyles)) {
      $passes++;
      echo "testGetSearchResultStyles: Style retrieved successfully. -PASS-\n";
    } else {
      $fails++;
      echo "testGetSearchResultStyles: Style retrieval failed. -FAIL-\n";
    }
    $this->_doPassFailOutput($passes, $fails, 'testGetSearchResultStyles');
  }

  function testGetBuiltinSearchResultStyles() {
    global $SENSAPILITY_CLIENTS;
    global $SENSAPILITY_AUTH;

    $passes = 0;
    $fails = 0;

    $newAcct = $this->makeNewAccount("SearchAds");

    $idArray = array();
    $keys = array_keys($newAcct);
    $pubId = $newAcct[$keys[0]]['id'];
    $idArray['SearchAds'] = $pubId;
    $SENSAPILITY_AUTH->setPubIds($idArray);

    $afs = $SENSAPILITY_CLIENTS->getService('AdSenseForSearch');
    $resultStyles = $afs->getBuiltinSearchResultStyles();

    if (!is_null($resultStyles)) {
      $passes++;
      echo "testGetBuiltinSearchResultStyles: Builtin search styles " . 
           "retrieved. -PASS-\n";
    } else {
      $fails++;
      echo "testGetBuiltinSearchResultStyles: Builtin search result " . 
           "styles not retrieved -FAIL-\n";
    }
    $this->_doPassFailOutput($passes, 
                             $fails, 
                             'testGetBuiltinSearchResultStyles');
  }

  function testSaveSearchResultStyle() {
    global $SENSAPILITY_CLIENTS;
    global $SENSAPILITY_AUTH;

    $passes = 0;
    $fails = 0;

    $newAcct = $this->makeNewAccount("SearchAds");

    $idArray = array();
    $keys = array_keys($newAcct);
    $pubId = $newAcct[$keys[0]]['id'];
    $idArray['SearchAds'] = $pubId;
    $SENSAPILITY_AUTH->setPubIds($idArray);

    $afs = $SENSAPILITY_CLIENTS->getService('AdSenseForSearch');
    $existingStyles = $this->_countSearchResultStyles($pubId);

    $afs->saveSearchResultStyle($pubId, 
                                'myStyle1',
                                '#000000',
                                '#000000',
                                '#000000',
                                '#000000',
                                'www.apple.com',
                                50,
                                'Left',
                                'www.apple.com',
                                100,
                                '#000000',
                                '#000000',
                                '#000000',
                                '#000000');

    $newNumberOfStyles = $this->_countSearchResultStyles($pubId);
    
    if ($numberOfStyles + 1 == $newNumberOfStyles) {
      $passes++;
      echo "testSaveSearchResultStyle: Style saved successfully. -PASS-\n";
    } else {
      $fails++;
      echo "testSaveSearchResultStyle: Style not saved.-FAIL-\n";
    }

    $this->_doPassFailOutput($passes, $fails, 'testSaveSearchResultStyle');
  }

  function testSaveSearchResultStyles(){
    global $SENSAPILITY_CLIENTS;
    global $SENSAPILITY_AUTH;

    $passes = 0;
    $fails = 0;

    $newAcct = $this->makeNewAccount("SearchAds");

    $idArray = array();
    $keys = array_keys($newAcct);
    $pubId = $newAcct[$keys[0]]['id'];
    $idArray['SearchAds'] = $pubId;
    $SENSAPILITY_AUTH->setPubIds($idArray);

    $afs = $SENSAPILITY_CLIENTS->getService('AdSenseForSearch');
    $existingStyles = $this->_countSearchResultStyles($pubId);

    $styles = array();
    $style1 = array('name' => 'myStyle1',
                    'borderColor' => '#000000',
                    'backgroundColor' => '#000000',
                    'faintTextColor' => '#000000',
                    'logoBackgroundColor' => '#000000',
                    'logoDestUrl' => 'www.apple.com',
                    'logoHeight' => 50,
                    'logoPlacement' => 'Left',
                    'logoUrl' => 'www.apple.com',
                    'logoWidth' => 100,
                    'textColor' => '#000000',
                    'titleColor' => '#000000',
                    'urlColor' => '#000000',
                    'visitedUrlColor' => '#000000');
    $style2 = array('name' => 'myStyle2',
                    'borderColor' => '#000000',
                    'backgroundColor' => '#000000',
                    'faintTextColor' => '#000000',
                    'logoBackgroundColor' => '#000000',
                    'logoDestUrl' => 'www.apple.com',
                    'logoHeight' => 50,
                    'logoPlacement' => 'Left',
                    'logoUrl' => 'www.apple.com',
                    'logoWidth' => 100,
                    'textColor' => '#000000',
                    'titleColor' => '#000000',
                    'urlColor' => '#000000',
                    'visitedUrlColor' => '#000000');
    $styles[0] = $style1;
    $styles[1] = $style2;
    $afs->saveSearchResultStyles($pubId, 
                                 $styles, 
                                 'testDeleteSearchResultStyle');
   
    $newNumberOfStyles = $this->_countSearchResultStyles($pubId);

    if ($existingStyles + 2 == $newNumberOfStyles) {
      echo "Style saved successfully.\n";
    } else {
      echo "Style not saved.\n";
    }
  }

  function _countSearchResultStyles($pubId){
    global $SENSAPILITY_CLIENTS;

    $afs = $SENSAPILITY_CLIENTS->getService('AdSenseForSearch');
    $existingStyles = $afs->getSearchResultStyles($pubId);
    
    $numberOfStyles = 0;
    $keys = array_keys($existingStyles);
    foreach ($keys as $key) {
      $numberOfStyles ++;
    }
    return $numberOfStyles;
  }

  function testDeleteSearchResultStyle() {
    global $SENSAPILITY_CLIENTS;
    global $SENSAPILITY_AUTH;

    $passes = 0;
    $fails = 0;

    $newAcct = $this->makeNewAccount("SearchAds");

    $idArray = array();
    $keys = array_keys($newAcct);
    $pubId = $newAcct[$keys[0]]['id'];
    $idArray['SearchAds'] = $pubId;
    $SENSAPILITY_AUTH->setPubIds($idArray);

    $afs = $SENSAPILITY_CLIENTS->getService('AdSenseForSearch');
    $originalNumberOfStyles = $this->_countSearchResultStyles($pubId);
    // make styleName a variable since we want to delete the same thing below
    $styleName = 'myStyle';
    $style = array('name' => $styleName,
                   'borderColor' => '#000000',
                   'backgroundColor' => '#000000',
                   'faintTextColor' => '#000000',
                   'logoBackgroundColor' => '#000000',
                   'logoDestUrl' => 'www.apple.com',
                   'logoHeight' => 50,
                   'logoPlacement' => 'Left',
                   'logoUrl' => 'www.apple.com',
                   'logoWidth' => 100,
                   'textColor' => '#000000',
                   'titleColor' => '#000000',
                   'urlColor' => '#000000',
                   'visitedUrlColor' => '#000000');
    $afs->saveSearchResultStyles($pubId, array($style));
    $newNumberOfStyles = $this->_countSearchResultStyles($pubId);

    if ($newNumberOfStyles - $originalNumberOfStyles == 1) {
      $passes += 1;
      echo "Style saved correctly. -PASS-\n";
    } else {
      // automatically fail the second test, because we know it won't succeed
      $fails += 2;
      echo "Style not saved. -FAIL-\n";
      return $this->_doPassFailOutput($passes, 
                                      $fails, 
                                      'testDeleteSearchResultStyle');
    }

    $afs->deleteSearchResultStyle($pubId, $styleName);
    $newNumberOfStyles = $this->_countSearchResultStyles($pubId);

    if ($newNumberOfStyles == $originalNumberOfStyles) {
      $passes += 1;
      echo "Style deleted correctly. -PASS-\n";
    } else {
      $fails += 1;
      echo "Style not deleted. -FAIL-\n";
    }

    $this->_doPassFailOutput($passes, $fails, 'testDeleteSearchResultStyle');
  }

  function _doPassFailOutput($passes, $fails, $testName = 'undefined') {
    echo "Test report for '" . $testName . "':\nPasses - " . 
         $passes . "\nFails - " . $fails . "\n\n";
  }

  function testDeleteSearchResultStyles() {
    global $SENSAPILITY_CLIENTS;
    global $SENSAPILITY_AUTH;

    $passes = 0;
    $fails = 0;

    $newAcct = $this->makeNewAccount("SearchAds");

    $idArray = array();
    $keys = array_keys($newAcct);
    $pubId = $newAcct[$keys[0]]['id'];
    $idArray['SearchAds'] = $pubId;
    $SENSAPILITY_AUTH->setPubIds($idArray);

    $afs = $SENSAPILITY_CLIENTS->getService('AdSenseForSearch');
    $originalNumberOfStyles = $this->_countSearchResultStyles($pubId);

    $styles = array();
    $firstStyleName = 'myStyle1';
    $secondStyleName = 'myStyle2';
    $style1 = array('name' => $firstStyleName,
                    'borderColor' => '#000000',
                    'backgroundColor' => '#000000',
                    'faintTextColor' => '#000000',
                    'logoBackgroundColor' => '#000000',
                    'logoDestUrl' => 'www.apple.com',
                    'logoHeight' => 50,
                    'logoPlacement' => 'Left',
                    'logoUrl' => 'www.apple.com',
                    'logoWidth' => 100,
                    'textColor' => '#000000',
                    'titleColor' => '#000000',
                    'urlColor' => '#000000',
                    'visitedUrlColor' => '#000000');
    $style2 = array('name' => $secondStyleName,
                    'borderColor' => '#000000',
                    'backgroundColor' => '#000000',
                    'faintTextColor' => '#000000',
                    'logoBackgroundColor' => '#000000',
                    'logoDestUrl' => 'www.apple.com',
                    'logoHeight' => 50,
                    'logoPlacement' => 'Left',
                    'logoUrl' => 'www.apple.com',
                    'logoWidth' => 100,
                    'textColor' => '#000000',
                    'titleColor' => '#000000',
                    'urlColor' => '#000000',
                    'visitedUrlColor' => '#000000');
    $styles[0] = $style1;
    $styles[1] = $style2;
    $afs->saveSearchResultStyles($pubId, $styles);
   
    $newNumberOfStyles = $this->_countSearchResultStyles($pubId);
    if ($newNumberOfStyles - $originalNumberOfStyles == 2) {
      $passes += 1;
      echo "Styles saved correctly. -PASS-\n";
    } else {
      $fails += 2;
      echo "Styles not saved. -FAIL-\n";
      return $this->_doPassFailOutput($passes, 
                                      $fails, 
                                      'testDeleteSearchResultStyles');
    }

    $deleteStyles = array();
    $deleteStyles[0] = $firstStyleName;
    $deleteStyles[1] = $secondStyleName;
    $afs->deleteSearchResultStyles($pubId, $deleteStyles);

    $newNumberOfStyles = $this->_countSearchResultStyles($pubId);
    if ($newNumberOfStyles == $originalNumberOfStyles) {
      $passes += 1;
      echo "Styles deleted correctly. -PASS-\n";
    } else {
      $fails += 1;
      echo "Styles not deleted correectly. -FAIL-\n";
    }

    $this->_doPassFailOutput($passes, $fails, 'testDeleteSearchResultStyles');
  }

  function testGetReferralData() {
    global $SENSAPILITY_CLIENTS;
    global $SENSAPILITY_AUTH;

    $passes = 0;
    $fails = 0;

    $newAcct = $this->makeNewAccount('ReferralAds');

    $idArray = array();
    $keys = array_keys($newAcct);
    $pubId = $newAcct[$keys[0]]['id'];
    $idArray['ReferralAds'] = $pubId;
    $SENSAPILITY_AUTH->setPubIds($idArray);

    $ref = $SENSAPILITY_CLIENTS->getService('Referral');
    $refData = $ref->getReferralData($pubId, 'en_US', 'AdSense'); 
    if ( !is_null($refData) ) {
      $passes += 1;
      echo "Ad code generated correctly. -PASS-\n";
    } else {
      $fails += 1;
      echo "Ad code generation failed. -FAIL-\n";
    }

    $this->_doPassFailOutput($passes, $fails, 'testGetReferralData');
  }

  function testSiteFilterService() {
    global $SENSAPILITY_CLIENTS;
    global $SENSAPILITY_AUTH;

    $passes = 0;
    $fails = 0;

    $newAcct = $this->makeNewAccount('ContentAds');

    $idArray = array();
    $keys = array_keys($newAcct);
    $pubId = $newAcct[$keys[0]]['id'];
    $idArray['ContentAds'] = $pubId;
    $SENSAPILITY_AUTH->setPubIds($idArray);
    
    $sfs = $SENSAPILITY_CLIENTS->getService('SiteFilter');

    $afcFilters = $sfs->getSiteFilters($pubId);
    
    if (!is_null($afcFilters)) {
      $count = 0;
      if (is_array($afcFilters)) {
        $keys = array_keys($afcFilters);
        foreach ($keys as $key) {
          $count++;
        }
      }

      if ($count == 0) {
        $passes++;
        echo 'testSiteFilterService: Site filters retreived successfully' .
             ' with proper count of zero filters. -PASS-' . "\n";
      } else {
        $fails++;
        echo 'testSiteFilterService: Site filters retreived successfully' .
             ' but with improper count of filters:' . $count .
             '. -FAIL-' . "\n";
      }
    } else {
      $fails++;
      echo 'testSiteFilterService: Site filters not retreived successfully' .
           '. -FAIL-' . "\n";
    }

    $filtersToAdd = array('www.example2.com');
    $sfs->addSiteFilters($pubId, $filtersToAdd);

    $afcFilters = $sfs->getSiteFilters($pubId);
    
    if (!is_null($afcFilters)) {
      $count = 0;
      if (is_array($afcFilters)) {
        $keys = array_keys($afcFilters);
        foreach ($keys as $key) {
          $count++;
        }
      }

      if ($count == 1) {
        $passes++;
        echo 'testSiteFilterService: Addition of one site filter' . 
             ' one successful -PASS-' . "\n";
      } else {
        $fails++;
        echo 'testSiteFilterService: Addition of one site filter' .
             ' failed. -FAIL-' . "\n";
      }
    } else{
      $fails++;
      echo 'testSiteFilterService: Addition of one site filter' .
           ' failed. -FAIL-' . "\n";
    }

    $filtersToAdd = array('www.example.com', 'www.example3.com');
    $sfs->addSiteFilters($pubId, $filtersToAdd);

    $afcFilters = $sfs->getSiteFilters($pubId);
    
    if (!is_null($afcFilters)) {
      $count = 0;

      if (is_array($afcFilters)) {
        $keys = array_keys($afcFilters);
        foreach ($keys as $key) {
          $count++;
        }
      }

      if ($count == 3) {
        $passes++;
        echo 'testSiteFilterService: Addition of two site filters' . 
             ' successful -PASS-' . "\n";
      } else {
        $fails++;
        echo 'testSiteFilterService: Addition of two site filter' .
             ' failed. -FAIL-' . "\n";
      }
    } else{
      $fails++;
      echo 'testSiteFilterService: Addition of two site filter' .
           ' failed. -FAIL-' . "\n";
    }


    $filtersToAdd = array('www.example2.com');
    $sfs->setSiteFilters($pubId, $filtersToAdd);

    $afcFilters = $sfs->getSiteFilters($pubId);
    
    if (!is_null($afcFilters)) {
      $count = 0;
      if (is_array($afcFilters)) {
        $keys = array_keys($afcFilters);
        foreach ($keys as $key) {
          $count++;
        }
      }

      if ($count == 1) {
        $passes++;
        echo 'testSiteFilterService: Set of one site filter' . 
             ' successful -PASS-' . "\n";
      } else {
        $fails++;
        echo 'testSiteFilterService: Set of one site filter' .
             ' failed. -FAIL-' . "\n";
      }
    } else{
      $fails++;
      echo 'testSiteFilterService: Set of one site filter' .
           ' failed. -FAIL-' . "\n";
    }

    $filtersToAdd = array('www.example.com', 'www.example3.com');
    $sfs->setSiteFilters($pubId, $filtersToAdd);

    $afcFilters = $sfs->getSiteFilters($pubId);
    
    if (!is_null($afcFilters)) {
      $count = 0;
      if (is_array($afcFilters)) {
        $keys = array_keys($afcFilters);
        foreach ($keys as $key) {
          $count++;
        }
      }

      if ($count == 2) {
        $passes++;
        echo 'testSiteFilterService: Set of two site filterss' . 
             ' successful -PASS-' . "\n";
      } else {
        $fails++;
        echo 'testSiteFilterService: Set of two site filters' .
             ' failed. -FAIL-' . "\n";
      }
    } else{
      $fails++;
      echo 'testSiteFilterService: Set of two site filters' .
           ' failed. -FAIL-' . "\n";
    }

    $sfs->removeSiteFilters($pubId, $filtersToAdd);

    $afcFilters = $sfs->getSiteFilters($pubId);
    
    if (!is_null($afcFilters)) {
      $count = 0;
      if (is_array($afcFilters)) {
        $keys = array_keys($afcFilters);
        foreach ($keys as $key) {
          $count++;
        }
      }

      if ($count == 0) {
        $passes++;
        echo 'testSiteFilterService: Removal of two site filters' . 
             ' successful -PASS-' . "\n";
      } else {
        $fails++;
        echo 'testSiteFilterService: Removal of two site filters' .
             ' failed. -FAIL-' . "\n";
      }
    } else{
      $fails++;
      echo 'testSiteFilterService: Removal of two site filters' .
           ' failed. -FAIL-' . "\n";
    }

    $filtersToAdd = array('www.example.com');

    $sfs->setSiteFilters($pubId, $filtersToAdd);
    $sfs->removeSiteFilters($pubId, $filtersToAdd);

    if (!is_null($afcFilters)) {
      $count = 0;
      if (is_array($afcFilters)) {
        $keys = array_keys($afcFilters);
        foreach ($keys as $key) {
          $count++;
        }
      }

      if ($count == 0) {
        $passes++;
        echo 'testSiteFilterService: Removal of one site filter' . 
             ' successful -PASS-' . "\n";
      } else {
        $fails++;
        echo 'testSiteFilterService: Removal of one site filter' .
             ' failed. -FAIL-' . "\n";
      }
    } else{
      $fails++;
      echo 'testSiteFilterService: Removal of one site filter' .
           ' failed. -FAIL-' . "\n";
    }

    $this->_doPassFailOutput($passes, $fails, 'testSiteFilterService');
  }

  function testAfcChannelReport() {
    global $SENSAPILITY_CLIENTS;
    global $SENSAPILITY_AUTH;

    $passes = 0;
    $fails = 0;
    $pubIds = array('ContentAds' => 'ca-pub-6779513902694553');
    $SENSAPILITY_AUTH->setPubids($pubIds);

    $rpt = $SENSAPILITY_CLIENTS->getService('Report');
    $afc = $SENSAPILITY_CLIENTS->getService('AdSenseForContent');
    $urlChannels = $afc->getChannels($pubIds['ContentAds'],
                                     'Url');
    $customChannels = $afc->getChannels($pubIds['ContentAds'],
                                        'Custom');

    $urlChnData = $rpt->generateAfcChannelReport('2006-01-01T08:00:00.000Z',
                                                 '2006-12-31T08:00:00.000Z',
                                                 false,
                                                 null,
                                                 'CSV_Excel',
                                                 'Channel',
                                                 'Ad',
                                                 array($urlChannels[0]['id'], 
                                                       $urlChannels[1]['id']));
    if (!is_null($urlChnData)) {
      $passes++;
      echo "Url channel report call successful. -PASS-\n";
    } else {
      $fails++;
      echo "Url channel report call returned no results. -FAIL-\n";
    }

    $customChnData = $rpt->generateAfcChannelReport('2006-01-01T08:00:00.000Z',
                                                    '2006-12-31T08:00:00.000Z',
                                                    false,
                                                    null,
                                                    'CSV_Excel',
                                                    'Channel',
                                                    'Ad',
                                                    array(
                                                     $customChannels[0]['id'], 
                                                     $customChannels[1]['id'])
                                                    );
    if (!is_null($customChnData)) {
      $passes++;
      echo "Custom channel report call successful. -PASS-\n";
    } else {
      $fails++;
      echo "Custom channel report call returned no results. -FAIL-\n";
    }

    $this->_doPassFailOutput($passes, $fails, 'testAFCChannelReport');
  }

  function testAfcAggregateReport() {
    global $SENSAPILITY_CLIENTS;
    global $SENSAPILITY_AUTH;

    $passes = 0;
    $fails = 0;
    $pubIds = array('ContentAds' => 'ca-pub-6779513902694553');
    $SENSAPILITY_AUTH->setPubids($pubIds);

    $rptSrvc = $SENSAPILITY_CLIENTS->getService('Report');
    $rpt = $rptSrvc->generateAFCAggregateReport('2006-01-01T08:00:00.000Z',
                                                '2006-12-31T08:00:00.000Z',
                                                false,
                                                null,
                                                'CSV_Excel',
                                                'Ad');

    if (!is_null($rpt)) {
      $passes++;
      echo "AFC aggregate report call successful. -PASS-\n";
    } else {
      $fails++;
      echo "AFC aggregate report call returned no results. -FAIL-\n";
    }
    $this->_doPassFailOutput($passes, $fails, 'testAFCAggregateReport');
  }

  function testAFSAggregateReport() {
    global $SENSAPILITY_CLIENTS;
    global $SENSAPILITY_AUTH;

    $passes = 0;
    $fails = 0;
    $pubIds = array('ContentAds' => 'ca-pub-6779513902694553');
    // library will automatically discover the other ids
    $SENSAPILITY_AUTH->setPubids($pubIds);

    $rptSrvc = $SENSAPILITY_CLIENTS->getService('Report');
    $rpt = $rptSrvc->generateAFSAggregateReport('2006-01-01T08:00:00.000Z',
                                                '2006-12-31T08:00:00.000Z',
                                                false,
                                                null,
                                                'CSV_Excel');
    if (!is_null($rpt)) {
      $passes += 1;
      echo "AFS aggregate report call successful. -PASS-\n";
    } else {
      $fails += 1;
      echo "AFS aggregate report call returned no results. -FAIL-\n";
    }
    $this->_doPassFailOutput($passes, $fails, 'testAFSAggregateReport');
  }

  function testAfsChannelReport() {
    global $SENSAPILITY_CLIENTS;
    global $SENSAPILITY_AUTH;

    $passes = 0;
    $fails = 0;
    $pubIds = array('ContentAds' => 'ca-pub-6779513902694553');
    $SENSAPILITY_AUTH->setPubids($pubIds);
    $pubIds = $SENSAPILITY_AUTH->getPubIds();

    $rpt = $SENSAPILITY_CLIENTS->getService('Report');
    $afs = $SENSAPILITY_CLIENTS->getService('AdSenseForSearch');
    $urlChannels = $afs->getChannels($pubIds['SearchAds'],
                                     'Url');
    $customChannels = $afs->getChannels($pubIds['SearchAds'],
                                        'Custom');

    $urlChnData = $rpt->generateAfsChannelReport('2006-01-01T08:00:00.000Z',
                                                 '2006-12-31T08:00:00.000Z',
                                                 false,
                                                 null,
                                                 'CSV_Excel',
                                                 'Channel',
                                                 array($urlChannels[1]['id'], 
                                                       $urlChannels[0]['id']));
    if (!is_null($urlChnData)) {
      $passes++;
      echo "Url channel report call successful. -PASS-\n";
    } else {
      $fails++;
      echo "Url channel report call returned no results. -FAIL-\n";
    }

    $customChnData = $rpt->generateAFSChannelReport('2006-01-01T08:00:00.000Z',
                                                    '2006-12-31T08:00:00.000Z',
                                                    false,
                                                    null,
                                                    'CSV_Excel',
                                                    'Channel',
                                                    array(
                                                     $customChannels[0]['id'], 
                                                     $customChannels[1]['id'])
                                                    );
    if (!is_null($customChnData)) {
      $passes++;
      echo "Custom channel report call successful. -PASS-\n";
    } else {
      $fails++;
      echo "Custom channel report call returned no results. -FAIL-\n";
    }

    $this->_doPassFailOutput($passes, $fails, 'testAFSChannelReport');
  }

  function testAFSQueryReport() {
    global $SENSAPILITY_CLIENTS;
    global $SENSAPILITY_AUTH;

    $passes = 0;
    $fails = 0;
    $pubIds = array('ContentAds' => 'ca-pub-6779513902694553');
    // library will automatically discover the other ids
    $SENSAPILITY_AUTH->setPubids($pubIds);

    $rptSrvc = $SENSAPILITY_CLIENTS->getService('Report');
    $rpt = $rptSrvc->generateAfsQueryReport('2006-01-01T08:00:00.000Z',
                                            '2006-12-31T08:00:00.000Z',
                                            false,
                                            null,
                                            'CSV_Excel');
    if (!is_null($rpt)) {
      $passes++;
      echo "AFS query report call successful. -PASS-\n";
    } else {
      $fails++;
      echo "AFS query report call returned no results. -FAIL-\n";
    }
    $this->_doPassFailOutput($passes, $fails, 'testAFSQueryReport');
  }

  function testReferralAggregateReport() {
    global $SENSAPILITY_CLIENTS;
    global $SENSAPILITY_AUTH;

    $passes = 0;
    $fails = 0;
    $pubIds = array('ContentAds' => 'ca-pub-6779513902694553');
    // library will automatically discover the other ids
    $SENSAPILITY_AUTH->setPubids($pubIds);

    $rptSrvc = $SENSAPILITY_CLIENTS->getService('Report');
    $rpt = $rptSrvc->generateReferralAggregateReport('2006-01-01T08:00:00.000Z',
                                                     '2006-12-31T08:00:00.000Z',
                                                     false,
                                                     null,
                                                     'CSV_Excel');
    if (!is_null($rpt)) {
      $passes++;
      echo "Referral aggregate report call successful. -PASS-\n";
    } else {
      $fails++;
      echo "Referral aggregate report call returned no results. -FAIL-\n";
    }
    $this->_doPassFailOutput($passes, $fails, 'testReferralAggregateReport');
  }

  function testReferralProductReport() {
    global $SENSAPILITY_CLIENTS;
    global $SENSAPILITY_AUTH;

    $passes = 0;
    $fails = 0;
    $pubIds = array('ContentAds' => 'ca-pub-6779513902694553');
    $SENSAPILITY_AUTH->setPubids($pubIds);

    $rptSrvc = $SENSAPILITY_CLIENTS->getService('Report');
    
    $rpt = $rptSrvc->generateReferralProductReport('2006-01-01T08:00:00.000Z',
                                                   '2006-12-31T08:00:00.000Z',
                                                   false,
                                                   null,
                                                   'CSV_Excel',
                                                   'Date',
                                                   array('AdSense'));
    if (!is_null($rpt)) {
      $passes++;
      echo "Referral product report call successful. -PASS-\n";
    } else {
      $fails++;
      echo "Referral product report call returned no results. -FAIL-\n";
    }
    $this->_doPassFailOutput($passes, $fails, 'testReferralProductReport');
  }
}
?>
